
<template>
  <div class="modal">
    <div class="modal-view api-import flex-cloumn">
      <div class="modal-view-head flex-row-center flex-row-between">
        <label>文档导入</label>
      </div>
      <div class="modal-view-body" @drop="fileUpload" @dragover="preventEvent">
        <transition name="anim-loading">
          <div class="import-remote-view abs flex-column" v-if="apiRemoteVisible" @drop="fileUpload" @dragover="preventEvent">
            <div class="import-remote flex-row-center">
              <div class="label">文档地址</div>
              <div class="input">
                <input maxlength="2048" v-model="apiRemoteUrl" placeholder="输入远程文档地址" />
              </div>
              <div class="btn-text click" @click="getApiDocRemote()">
                <Icon class="icon" type="download" />获取
              </div>
            </div>
            <div class="abs loading flex-center" size="large" fix v-if="ajax?true:false">
              <Icon type="refresh" class="ajax-loading"></Icon>
              <div>Loading...</div>
            </div>
            <br />
            <div class="flex-center warning">确保远程文档允许跨域访问</div>
            <br />
            <div v-if="apiImportDocInfo" class="flex-center error">{{apiImportDocInfo}}</div>
          </div>
        </transition>
        <div class="api-import-info flex-column">
          <div v-if="apiImportDoc" class="api-doc-info">
            <div class="api-item flex-start">
              <label class="label">文档名称 :</label>
              {{apiImportDoc.name||"无"}}
            </div>

            <div class="api-item flex-start">
              <label class="label">更新时间 :</label>
              {{apiImportDoc.updateTime||"无"}}
            </div>
            <div class="api-item flex-start">
              <label class="label">文档详情 :</label>
              <div class="textarea">
                <textarea class="textarea" maxlength="20480" :value="apiImportDocStr" />
              </div>
            </div>
          </div>
          <div v-if="!apiImportDoc" class="api-doc-info flex-column-center">
            <div v-if="apiImportDocInfo" class="aux">{{apiImportDocInfo}}</div>
            <label class="btn-import flex-row-center" @click="ev=>$refs['inputUpload'].click()">
              <Icon class="icon" type="download" />导入文档
            </label>
          </div>
        </div>
        <input
          type="file"
          class="iframe-api-import"
          ref="inputUpload"
          @change="fileUpload"
          placeholder
        />
        <iframe class="iframe-api-import" name="importDoc" ref="importDoc" />
      </div>
      <div class="modal-view-footer flex-row-between">
        <div class="time flex-row-center">
          <span class="btn click" @click="apiRemoteVisible=!apiRemoteVisible">远程文档</span>
        </div>
        <div>
          <transition name="anim-opacity">
            <span v-if="apiImportDoc" class="btn" @click="$emit('ok',apiImportDoc)">确认</span>
          </transition>
          <span class="btn" @click="$emit('close')">关闭</span>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
export default {
  props: ["url"],
  data: function() {
    return {
      ajax: null,
      apiRemoteVisible: false,
      apiRemoteUrl: this.url || "",
      apiImportDoc: null,
      apiImportDocInfo: ""
    };
  },
  computed: {
    apiImportDocStr() {
      if (!this.apiImportDoc) {
        return "无";
      }
      return JSON.stringify(this.apiImportDoc, null, 2);
    }
  },
  mounted() {},
  beforeUnmount() {
    this.ajax = window.axios.CancelToken.source();
  },
  methods: {
    preventEvent(ev) {
      ev.preventDefault();
      ev.stopPropagation();
    },
    setApiDocImport(docStr = "") {
      let reg = new RegExp('(<script id="ApiDocScript">)(.+?)(</scrip' + "t>)");
      let str = reg.exec(docStr) || [];
      let apiDocStr = str[2];
      if (!apiDocStr) {
        apiDocStr = " var apiDoc = " + docStr;
      }
      let scriptStr = `<script>${apiDocStr}</scrip` + "t>";
      this.$refs["importDoc"].contentWindow.apiDoc = null;
      this.$refs["importDoc"].contentWindow.document.write(scriptStr);
      let apiDoc = this.$refs["importDoc"].contentWindow.apiDoc;
      if (apiDoc) {
        this.apiImportDoc = JSON.parse(JSON.stringify(apiDoc));
      }
      return apiDoc;
    },
    fileUpload(ev) {
      this.apiImportDoc = null;
      this.apiImportDocInfo = null;

      let taget = ev.target;
      ev.type == "drop" && (taget = ev.dataTransfer);
      let file = ((taget || {}).files || [])[0];
      // console.log("=========1", file);
      if (file.size > 1048576 * 200) {
        return (this.apiImportDocInfo = `请选择200M以内的文档`);
      }
      if (!file) {
        return;
      }

      let reader = new FileReader();
      reader.readAsText(file);
      reader.onload = (res, error) => {
        if (!this.setApiDocImport(reader.result)) {
          this.apiImportDocInfo = `[${file.name}]不是正确的文档`;
        }
      };
    },
    getApiDocRemote(cancel) {
      this.ajax && this.ajax.cancel("取消调试");
      if (cancel) {
        return (this.ajax = false);
      }
      let url = this.apiRemoteUrl;
      if (!url) {
        return (this.apiImportDocInfo = `输入远程文档地址`);
      }

      this.apiImportDocInfo = null;
      this.apiImportDoc = null;
      this.ajax = window.axios.CancelToken.source();
      let option = {
        method: "get",
        url: url,
        cancelToken: this.ajax.token
      };
      this.$ajax(option).then(result => {
        this.ajax = null;
        // console.log(result);
        if (!this.setApiDocImport(result)) {
          this.apiImportDocInfo = `远程文档[${url}]不是正确的文档`;
        } else {
          this.apiRemoteVisible = false;
        }
      });
    }
  }
};
</script>
<style>
.api-import {
  width: 80%;
  max-width: 480px;
  min-width: 260px;
}
.iframe-api-import {
  display: none;
  position: absolute;
}
.api-import-info {
  height: 200px;
  /* cursor: pointer; */
  border: 1px dashed #916a3037;
  border-radius: 5px;
  transition: 0.3s;
  overflow: hidden;
  padding: 5px;
}
.api-import-info .textarea {
  height: 130px;
}
.api-doc-info {
  overflow: auto;
  flex-grow: 1;
  height: auto;
  max-height: 100%;
}
.btn-import {
  margin: 10px;
  padding: 3px 10px;
  border: 1px dashed #db821c53;
  /* background-color: #ddd7; */
  border-radius: 3px;
  cursor: pointer;
  color: #db821c;
  line-height: 0;
}
.btn-import .icon {
  width: 28px;
  height: 28px;
  fill: #b8a894;
}

.import-remote-view {
  padding: 10px;
  background-color: #fffe;
  z-index: 1;
}
.import-remote {
  /* margin: 5px 0; */
  margin-bottom: 10px;
  border: 1px solid #916a3047;
  border-radius: 3px;
}
.import-remote input {
  border-color: transparent;
}
.import-remote .input {
  border-right: 1px solid #916a3047;
  border-left: 1px solid #916a3047;
}
.import-remote .label {
  margin: 0;
  display: block;
  text-align: center;
  width: auto;
}
.import-remote .btn {
  padding: 0 5px;
  opacity: 0.5;
}
.api-import-info:hover {
  border-color: #916a30a7;
}
</style>